<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getSysList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :pagination="false"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader v-if="thisPermission.update">
        <el-button v-if="!isEdit" type="primary" :disabled="proTable && proTable.tableData.length === 0" @click="openEdit">
          编辑
        </el-button>
        <el-button v-if="isEdit" @click="changeEdit">取消</el-button>
        <el-button v-if="isEdit" type="primary" @click="submitForm" :loading="isEditLoading">提交</el-button>
      </template>
      <!-- value -->
      <template #value="scope">
        <span v-if="!isEdit">{{ scope.row.value }}</span>
        <div v-else>
          <el-input-number
            :disabled="!scope.row.editable"
            :min="scope.row.rule.min"
            :max="scope.row.rule.max"
            controls-position="right"
            :precision="0"
            v-model="editForm[scope.row.key].value"
          />
        </div>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="ts" name="SysSetting">
import { ref, computed, reactive } from "vue";
import { useRoute } from "vue-router";
import { useAuthStore } from "@/stores/modules/auth";
import ProTable from "@/components/ProTable/index.vue";
import { Sys } from "@/api/interface/sysManagement";
import { getSysList, updateSys } from "@/api/modules/sysManagement/sysSetting";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";

const route = useRoute();
const authStore = useAuthStore();
const thisPermission = computed(() => authStore.permissionListGet[route.name as string] || {});
const isEdit = ref(false);
const isEditLoading = ref(false);
const editForm = reactive({});
const proTable = ref<ProTableInstance>();
const initParam = reactive({ category: "SECURITY" });

const dataCallback = (data: any) => {
  return data.filter(item => item.key !== "MULTI_LOGIN");
};

// 表格配置项
const columns = reactive<ColumnProps<Sys.ResSysList>[]>([
  { prop: "name", label: "配置项信息" },
  { prop: "value", label: "配置项值", width: 180 },
  { prop: "desc", label: "配置项说明" }
]);

const changeEdit = () => {
  isEdit.value = !isEdit.value;
};

const openEdit = () => {
  proTable.value?.tableData.forEach(item => {
    editForm[item.key] = {
      value: item.value,
      enable: true
    };
  });
  changeEdit();
};

const submitForm = async () => {
  isEditLoading.value = true;
  await updateSys(editForm);
  proTable.value?.getTableList();
  changeEdit();
  isEditLoading.value = false;
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
